/**
 * 
 */
package com.app.service;

import com.app.mapper.IBaseMapper;
import com.app.model.wrapper.Order;
import com.app.model.wrapper.RollPage;
import com.frame.utils.ClearNullUtil
import groovy.transform.CompileStatic
import groovy.transform.TypeChecked;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;


/**
 * 基本Service实现类
 * @author 张斌
 *
 */
@CompileStatic
@TypeChecked
abstract class BaseService<M> implements IBaseService<M>{

    protected Integer pageSizeDefault = 20 //PropertiesConstant.getGlobalString("global.pageSize") as int;

    protected IBaseMapper<M> baseMapper

    void setBaseMapper(IBaseMapper<M> baseMapper) {
        this.baseMapper = baseMapper
    }

    abstract <K> K addBasic(M obj) throws Exception

    abstract void modifyBasic(M obj) throws Exception

    abstract void delBasic(M obj) throws Exception

    @Override
    public <K> M findObjByKey(K seq) throws Exception {
        baseMapper.selectByPrimaryKey(seq)
    }

    @Override
    M findObj(Map<String, Object> params) throws Exception {
        ClearNullUtil.mapClear(params)
        baseMapper.selectByParams(params)
    }

    @Override
    List<M> findListByParams(Map<String, Object> params, Order order) throws Exception {
        ClearNullUtil.mapClear(params)
        baseMapper.selectListByParams(params,null,null,order?.toString())
    }

    @Override
    Integer findCountByParams(Map<String, Object> params) {
        return baseMapper.selectCountByParams(params)
    }

    @Override
    List<M> findListByParams(Map<String, Object> params, Order order, Integer maxRecord) throws Exception {
        ClearNullUtil.mapClear(params)
        baseMapper.selectListByParams(params, 0, maxRecord, order?.toString())
    }

    @Override
    RollPage<M> findListPageByParams(Map<String, Object> params, Order order, Integer pageNum, Integer pageSize) throws Exception {
        ClearNullUtil.mapClear(params)
        Integer recordSum= baseMapper.selectCountByParams(params)
        RollPage rollPage=new RollPage(recordSum: recordSum, pageSize:pageSize?:this.pageSizeDefault,pageNum: pageNum?:1)

        Integer<M> pageOffset=(rollPage.getPageNum() - 1) * rollPage.getPageSize()

        if (recordSum>0) {
            rollPage.recordList =baseMapper.selectListByParams(params, pageOffset, rollPage.pageSize, order?.toString())
        }
        else{
            rollPage.recordList = []
        }

        rollPage;
    }
}

